package com.springboot.core;

import java.util.HashMap;
import java.util.Map;

/**
 * On 2016/11/29 0029.
 *
 * @description web缓存管理
 */
public class MCacheManager {
    private static Map<String, ExpiryObject> cache = new HashMap<>(16, 0.75f);

    public static Object get(String key) {
        return get(key, Object.class);
    }

    /**
     * @param key   键名
     * @param clazz 返回的实例类型
     * @param <T>   返回对象
     * @return T类型对象
     */
    public static <T> T get(String key, Class<T> clazz) {
        ExpiryObject expiryObject = cache.get(key);
        if(null == expiryObject){
            return null;
        }
        if (expiryObject.expiryTime != 0 && expiryObject.expiryTime < System.currentTimeMillis()) {
            cache.remove(key, expiryObject);
            return null;
        } else {
            return clazz.cast(expiryObject.Obj);
        }
    }

    public static <T> void put(String key, T value) {
        put(key, value, 0);
    }

    /**
     * @param key     对应的键名
     * @param value   对应的值
     * @param timeOut 超时时间 ，0为不过期  ，毫秒级
     * @param <T>     存入的类型
     */
    public static <T> void put(String key, T value, long timeOut) {
        ExpiryObject<T> expiryObject = new ExpiryObject<>();
        if (timeOut != 0)
            expiryObject.expiryTime = System.currentTimeMillis() + timeOut;
        else
            expiryObject.expiryTime = timeOut;
        expiryObject.Obj = value;
        cache.put(key, expiryObject);
    }

    private static class ExpiryObject<T> {
        long expiryTime;
        T Obj;
    }

    public static void main(String[] args) throws InterruptedException {
//        MCacheManager.put("key", 123, 2000);
//        TimeUnit.SECONDS.sleep(1);
        Integer res = MCacheManager.get("key", Integer.class);
        System.out.println(res);
    }

}
